<?php

namespace backend\modules\wechat\controllers;

use backend\controllers\AdminController;
use common\models\wechat\WechatAccounts;
use common\models\wechat\WechatFansGroups;
use yii\helpers\ArrayHelper;

class FansGroupsController extends AdminController
{


    public function actionIndex()
    {
        $model = WechatFansGroups::findOne(['wid'=>WechatAccounts::WID]);
        if(empty($model)){
            WechatFansGroups::getFansGroups();
            $model = WechatFansGroups::findOne(['wid'=>WechatAccounts::WID]);
        }
        $data = unserialize($model->groups);
        return $this->render('index',[
            'data' => $data['tags']
        ]);
    }


    /**
     * @return string
     * 新建
     */
    public function actionCreate()
    {
        $model = WechatFansGroups::findOne(['wid'=>WechatAccounts::WID]);
        if(\Yii::$app->request->isPost){
            if(empty(\Yii::$app->request->post('name'))){
                return $this->dialog('标签不能为空');
            }
            $model->createTags(\Yii::$app->request->post('name'));
            return $this->redirect('index');
        }
        return $this->render('create');
    }


    /**
     * @return string
     * 更新
     */
    public function actionUpdate($tagid)
    {
        $model = WechatFansGroups::findOne(['wid'=>WechatAccounts::WID]);
        if(\Yii::$app->request->isPost){
            if(\Yii::$app->request->post('name') == \Yii::$app->request->post('oldname')){
                return $this->dialog('您没有进行任何的更改');
            }

            if(empty(\Yii::$app->request->post('name'))){
                return $this->dialog('标签不能为空');
            }
            $tagid = \Yii::$app->request->post('id');
            $tagname = \Yii::$app->request->post('name');
            $model->upTags($tagid,$tagname);
            return $this->redirect('index');
        }
        $data = unserialize($model->groups);
        $tagname = '';
        foreach ($data['tags'] as $key => $row){
            if($row['id'] == $tagid){
                $tagname = $row['name'];
            }
        }

        return $this->render('update',[
            'id' => $tagid,
            'name' => $tagname
        ]);
    }


    /**
     * @param $id
     * 删除
     */
    public function actionDelete($id)
    {
        $model = WechatFansGroups::findOne(['wid'=>WechatAccounts::WID]);
        $model->deleteTags($id);
        return $this->redirect('index');
    }


    public function actionRefresh()
    {
        WechatFansGroups::getFansGroups(true);
        return \GuzzleHttp\json_encode(['status'=>0,'msg'=>'刷新成功']);

    }


}



?>